<template>
  <div class="container">
    <div class="app-container">
      <div class="box">
        <el-button type="primary" size="mini" @click="dialogVisible = true ; isok=true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column
          label="角色"
          width="200"
          align="center"
          prop="name"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name " size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="启用"
          width="200"
          align="center"
          prop="state"
        >
          <template slot-scope="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              size="mini"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state===1?'已启用':(row.state===0?'未启用':'无') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="描述"
          align="center"
          prop="description"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="{row}">
            <template v-if="!row.isEdit">
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editor(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="removeRole(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="btnRow(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          small
          layout="prev, pager, next"
          :current-page="pageParams.page"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 添加角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="dialogVisible"
      width="500px"
      @close="btnONOk"
    >
      <el-form ref="form" label-width="120px" :rules="rules" :model="roleForm">
        <el-form-item label="角色名称" prop="name"><el-input v-model="roleForm.name" size="mini" style="width:300px" /></el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="roleForm.state"
            size="mini"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description"><el-input v-model="roleForm.description" size="mini" style="width:300px" type="textarea" :rows="3" /></el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="btnOk">确定</el-button>
              <el-button size="mini" @click="btnONOk">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置编辑角色 -->
    <el-dialog
      title="分配权限"
      :visible.sync="permissions"
    >
      <el-tree
        ref="tree"
        :data="treeDate"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        node-key="id"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="mini" type="primary" @click="btnPermOk">确定</el-button>
        <el-button size="mini" @click="permissions=false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, removeRole, modifyRole, getRole, distributionRole } from '@/api/role'
import { transListToTreeData } from '@/utils/index'
import { getPermission } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      dialogVisible: false, // 弹出层控制
      list: [], // 存放数据
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0// 总页数
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '请填写角色名称', trigger: 'blur' }]
      },
      permissions: false, // 控制分配权限开关
      treeDate: [], // 装树形结构的数据
      currentRoleId: null, // 自身id后续调接口用
      permIds: [] // 初始化是否勾选上
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.list.forEach(item => {
        // 这个方法很牛，可以使更改的数据变成响应式，第一个填需要改的数据，第二个是改的属性值，第三个为初始值
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    changePage(n) { // 这个事件是组件提供的
      // console.log(n)
      this.pageParams.page = n
      this.getRoleList()
    },
    // 点击取消添加按钮
    btnONOk() {
      // console.log(1)
      // this.roleForm = this.$options.data().roleForm
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    // 点击确定添加按钮
    btnOk() {
      this.$refs.form.validate(async isok => {
        if (isok) {
          // if (this.isok) {
          await addRole(this.roleForm)
          this.$message.success('新增成功')
          // } else {
          //   await modifyRole(this.roleForm.id, this.roleForm)
          //   this.$message.success('修改成功')
          // }
          this.getRoleList()
          this.btnONOk()
        }
      })
    },
    // 点击编辑行
    editor(row) {
      row.isEdit = true
      // 把表单重置
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 点击按钮删除
    async removeRole(id) {
      await removeRole(id)
      this.$message.success('删除成功')
      // 如果删除的是最后一条信息，就让页面回到上一页
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 点击确定修改个人信息
    async btnRow(row) {
      if (row.editRow.name.trim() && row.editRow.description.trim()) {
        // 拿到数据调修改接口
        await modifyRole({ ...row.editRow, id: row.id })
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        this.$message.success('修改成功')
      } else {
        this.$message.warning('请填写角色和介绍')
      }
    },
    async btnPermission(id) { // 分配权限按钮
      this.treeDate = transListToTreeData(await getPermission(), 0)
      const { permIds } = await getRole(id)
      this.permIds = permIds
      this.currentRoleId = id
      this.permissions = true
      // console.log(this.treeDate)
    },
    async btnPermOk() { // 分配权限点击确定
      await distributionRole({
        id: this.currentRoleId,
        permIds: this.$refs.tree.getCheckedKeys() // 这个方法是树形组件自带的
      })
      this.$message.success('分配成功')
      this.permissions = false
    }
  }
}

</script>

<style scoped>
.box {
  padding: 10px;

}
</style>
